package dm.ast;

import test.envset.GlobalState;

/**
 * select语句中的limit子句
 */
public class DmLimit extends DmASTNode{
    //LIMIT子句的4种格式
    public static int SUPPORT_FORMAT = 4;  //0: limit m 1: limit m ,n  2: limit m offset n 3: offset n limit m

    private int m = 0;
    private int n = 0;
    private int formatIndex = -1;  //实际使用的格式

    public void setM(int m) {
        this.m = m;
    }

    public void setN(int n) {
        this.n = n;
    }

    public void setFormat(int index) {
        this.formatIndex = index;
    }

    @Override
    public void fill(GlobalState globalState) {
        if(formatIndex == -1){
            formatIndex = 0;
            m = 1;
            n = 1;
        }
        isCompleted = true;
    }

    @Override
    public void setWidt() {
        //暂时不考虑复杂表达式
        wid_t = 2;
    }

    @Override
    public void setDept() {
        //暂时不考虑复杂表达式
        dep_t = 1;
    }

    @Override
    public DmDataType getExpressionType() {
        return null;
    }

    @Override
    public String toSql(){
        StringBuilder sql = new StringBuilder();
        if(formatIndex == -1){
            sql.append(" " + this.getClass().getSimpleName());
        }else {
            switch (formatIndex){
                case 1:
                    sql.append(String.format(" LIMIT %d , %d " , m , n));
                    break;
                case 2:
                    sql.append(String.format(" LIMIT %d OFFSET %d " , m , n));
                    break;
                case 3:
                    sql.append(String.format(" OFFSET %d LIMIT %d " , m , n));
                    break;
                default:
                    sql.append(String.format(" LIMIT %d " , m));
                    break;
            }
        }
        return sql.toString();
    }
}
